import socket
import select

server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind(('127.0.0.1',6666))
server.listen(10)

r = []
w = []
r.append(server)
m = ''
while True:
    rlist,wlist,xlist = select.select(r,[],[])
    for i in rlist:
        if i is server:
            con,add = i.accept()
            if con.recv(1024).decode('utf8') == 'YES':
                r.append(con)
                w.append(con)
            else:
                con.send('NO'.encode('utf8'))
                r.remove(i)
        else:
            try:
                m += i.recv(1024).decode('utf8')
                if not m or m =='NO':
                    print('客户端{}已断开连接'.format(i))
                    i.send('NO'.encode('utf8'))
                    i.close()
                    r.remove(i)
                    w.remove(i)
                else:
                    for i in w:
                        try:
                            i.send(('{}说：{}'.format(i,m)).encode('utf8'))
                        except:
                            i.colse()
                    m = ''
            except:
                i.close()

